package com.lb.trac.aop.handler;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.AbstractController;

import com.lb.trac.controller.common.loaders.HttpObjectsLoader;

public class HttpRequestInterceptor extends HandlerInterceptorAdapter {

	private Map<String, List<HttpObjectsLoader>> loaders;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String uri = request.getRequestURI();

		if (uri.lastIndexOf("/") != -1) {
			uri = uri.substring(uri.lastIndexOf("/"));
		}
		String suffix = uri.substring(uri.lastIndexOf("."));
		
		List<HttpObjectsLoader> loaders = getLoaders().get("/*"+suffix);

		if (loaders != null) {
			for (Iterator iterator = loaders.iterator(); iterator.hasNext();) {
				HttpObjectsLoader loader = (HttpObjectsLoader) iterator.next();

				loader.load(request, response);
			}
		}
		loaders = getLoaders().get(uri);
		if (loaders != null) {
			for (Iterator iterator = loaders.iterator(); iterator.hasNext();) {
				HttpObjectsLoader loader = (HttpObjectsLoader) iterator.next();

				loader.load(request, response);
			}
		}
		return super.preHandle(request, response, handler);
	}

	public Map<String, List<HttpObjectsLoader>> getLoaders() {
		return loaders;
	}

	public void setLoaders(Map<String, List<HttpObjectsLoader>> loaders) {
		this.loaders = loaders;
	}

}
